/**
 * Copyright (c) 2016-2019 HBZH All rights reserved.
 * <p>
 * https://www.hbzhit.com
 */

package com.hbzhit.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbzhit.common.utils.R;
import com.hbzhit.modules.sys.dao.SysUserTokenDao;
import com.hbzhit.modules.sys.entity.SysUserTokenEntity;
import com.hbzhit.modules.sys.oauth2.TokenGenerator;
import com.hbzhit.modules.sys.service.SysUserTokenService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * @author DING
 */
@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {

    @Override
    public R<Object> createToken(long userId, String tokenType) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //判断是否生成过token
        LambdaQueryWrapper<SysUserTokenEntity> query = new LambdaQueryWrapper<>();
        query.eq(SysUserTokenEntity::getUserId, userId);
        query.eq(SysUserTokenEntity::getTokenType, tokenType);
        SysUserTokenEntity tokenEntity = this.getOne(query);
        //无token
        if (tokenEntity == null) {
            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setTokenType(tokenType);
            tokenEntity.setUpdateTime(new Date());

            //保存token
            this.save(tokenEntity);
        } else {
            //如果token过期
            if (new Date().after(tokenEntity.getExpireTime())) {
                tokenEntity.setToken(token);
            }
            tokenEntity.setUpdateTime(new Date());

            //更新token
            this.updateById(tokenEntity);
        }
        
        return R.ok().put("token", tokenEntity.getToken())
                .put("expire", tokenEntity.getExpireTime())
                .put("userId", userId);
    }

    @Override
    public void logout(long userId, String tokenType) {
        SecurityUtils.getSubject().logout();
    }
}
